package jhavelogger.parser;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jhavelogger.models.AcceptedConnection;
import jhavelogger.models.UsernameLookup;
import jhavelogger.models.JHaveLog;
import jhavelogger.models.UnparsedLog;

/**
 * Parses "Up front with username" log messages. This specifies who actually
 * looked up the algorithm.
 * @author Jared Schlicht
 */
public class UsernameLookupFactory implements LogFactory {
    private Pattern pattern;

    public UsernameLookupFactory() {
	// "1/21/09 10:19 AM - FINE: Up front with user  naps@uwosh.edu looking for -- exe/dfsrichard/dfsrichard"
	final String datePattern = "\\d{1,2}/\\d{1,2}/\\d{2}";
	final String timePattern = "\\d{1,2}:\\d{1,2} (?:AM|PM)";
	final String algorithmLookupRegex = "^(?:" + datePattern + "\\s+" +
		timePattern + ")\\s+-\\s+FINE:\\s+Up\\s+front\\s+(?:with\\s+user\\s+([\\w@\\.]+)\\s*)?looking\\s+for\\s+--\\s+exe/(\\w+)/\\w+";
	this.pattern = Pattern.compile(algorithmLookupRegex, Pattern.CASE_INSENSITIVE);
    }

    @Override
    public JHaveLog create(UnparsedLog log) {
	Matcher matcher = this.pattern.matcher(log.getMessage());
	if (matcher.find()) {
	    String username = matcher.group(1);
	    if (username == null) {
		username = "no_username";
	    }
	    return new UsernameLookup(log.getSource(), username);
	}
	return null;
    }

}
